package com.gin.no_gay_alliance.utils;

import android.util.Log;

import androidx.annotation.FloatRange;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import java.lang.reflect.Field;

/**
 * 工具类
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/25 20:05
 **/
public class ViewPager2Utils {
    public static final String TAG = ViewPager2Utils.class.getSimpleName();

    /**
     * 修改ViewPager2的滑动灵敏度
     *
     * @param viewPager2 需要修改的实例
     * @param times      在原滑动举例基础上的倍率
     */
    public static void setTouchSlop(ViewPager2 viewPager2, @FloatRange(from = 0.1) double times) {
        try {
            // 反射获取ViewPager2其中的 RecyclerView实例
            final Field recyclerViewField = ViewPager2.class.getDeclaredField("mRecyclerView");
            recyclerViewField.setAccessible(true);
            final RecyclerView recyclerView = (RecyclerView) recyclerViewField.get(viewPager2);
            recyclerViewField.setAccessible(false);

            final Field touchSlopField = RecyclerView.class.getDeclaredField("mTouchSlop");
            touchSlopField.setAccessible(true);
            //通过获取原有的最小滑动距离 *n来增加此值
            Object oldValue = touchSlopField.get(recyclerView);
            int v = oldValue == null ? 100 : (int) oldValue;
            int newValue = (int) (v * times);
            touchSlopField.set(recyclerView, newValue);
            touchSlopField.setAccessible(false);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            Log.w(TAG, "灵敏度设置失败", e);
            e.printStackTrace();
        }
    }
}
